<template>
  <div class="opportunity-container">
    <!-- 页面头部，可以添加一些装饰性元素 -->
    <div class="page-header">
      <h2>探索机遇 · 成就未来</h2>
      <p class="subtitle">发现校园内外的精彩机会</p>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-input
        v-model="searchForm.title"
        placeholder="请输入机会标题搜索"
        class="search-input"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">搜索</el-button>
        </template>
      </el-input>
    </div>

    <!-- 分类列表 -->
    <div class="category-section">
      <el-radio-group v-model="searchForm.categoryId" @change="handleCategoryChange">
        <el-radio :label="null">全部</el-radio>
        <el-radio
          v-for="category in categories"
          :key="category.categoryId"
          :label="category.categoryId"
        >
          {{ category.categoryName }}
        </el-radio>
      </el-radio-group>
    </div>

    <!-- 机会列表 -->
    <div class="opportunity-list">
      <el-row :gutter="20">
        <el-col
          v-for="item in opportunityList"
          :key="item.opportunityId"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card
            class="opportunity-card"
            shadow="hover"
            @click="showOpportunityDetail(item.opportunityId)"
          >
            <img
              v-if="item.coverImage"
              :src="item.coverImage"
              class="opportunity-cover"
            />
            <div class="opportunity-info">
              <h3 class="opportunity-title">{{ item.title }}</h3>
              <div class="opportunity-stats">
                <span>
                  <el-icon><View /></el-icon>
                  {{ item.viewCount }}
                </span>
                <span>
                  <el-icon><ChatDotRound /></el-icon>
                  {{ item.commentCount }}
                </span>
              </div>
              <div class="opportunity-time">
                {{ formatRelativeTime(item.createTime) }}
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="searchForm.pageNum"
        v-model:page-size="searchForm.pageSize"
        :total="total"
        :page-sizes="[9, 18, 36, 72]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 机会详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="机会详情"
      width="60%"
      destroy-on-close
    >
      <opportunity-detail
        v-if="detailDialogVisible"
        :opportunity-id="currentOpportunityId"
        @close="detailDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { getOpportunityCategories, getOpportunityList } from '@/api/opportunity'
import { ElMessage } from 'element-plus'
import OpportunityDetail from './OpportunityDetail.vue'
import { View, ChatDotRound } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 数据状态
const opportunityList = ref([])
const categories = ref([])
const loading = ref(false)
const total = ref(0)
const detailDialogVisible = ref(false)
const currentOpportunityId = ref(null)

// 搜索表单
const searchForm = reactive({
  pageNum: 1,
  pageSize: 9,
  categoryId: null,
  title: '',
  opportunityStatus: null
})

// 格式化相对时间
const formatRelativeTime = (date) => {
  if (!date) return ''
  const now = new Date()
  const d = new Date(date)
  const diff = now - d
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 30) return `${days}天前`
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).format(d)
}

// 加载机会数据
const loadOpportunities = async () => {
  loading.value = true
  try {
    const res = await getOpportunityList(searchForm)
    console.log('机会列表响应:', res)
    if (res.code === 0 || res.code === 200) {
      opportunityList.value = res.data.records || []
      total.value = res.data.total || 0
      console.log('加载机会数据成功:', opportunityList.value.length, '条记录')
    } else {
      ElMessage.error(res.message || '获取机会列表失败')
    }
  } catch (error) {
    console.error('获取机会列表失败:', error)
    ElMessage.error('获取机会列表失败')
  } finally {
    loading.value = false
  }
}

// 加载分类数据
const loadCategories = async () => {
  try {
    const res = await getOpportunityCategories()
    console.log('分类列表响应:', res)
    if (res.code === 0 || res.code === 200) {
      categories.value = res.data || []
      console.log('加载分类数据成功:', categories.value.length, '个分类')
    } else {
      ElMessage.error(res.message || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 显示机会详情弹窗
const showOpportunityDetail = (opportunityId) => {
  currentOpportunityId.value = opportunityId
  detailDialogVisible.value = true
}

// 处理分类变化
const handleCategoryChange = (value) => {
  searchForm.categoryId = value
  searchForm.pageNum = 1
  loadOpportunities()
}

// 处理搜索
const handleSearch = () => {
  searchForm.pageNum = 1
  loadOpportunities()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  searchForm.pageSize = val
  searchForm.pageNum = 1
  loadOpportunities()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  searchForm.pageNum = val
  loadOpportunities()
}

// 页面初始化
onMounted(async () => {
  await loadCategories()
  loadOpportunities()
})
</script>

<style scoped>
.opportunity-container {
  padding: 2rem 4rem;
  background-color: #f8f9fa;
  min-height: calc(100vh - 64px);
}

.page-header {
  text-align: center;
  margin-bottom: 2.5rem;
}

.page-header h2 {
  font-size: 2.2rem;
  color: #333;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.subtitle {
  color: #666;
  font-size: 1.1rem;
}

.search-section {
  margin-bottom: 20px;
}

.search-input {
  max-width: 500px;
}

.category-section {
  margin-bottom: 20px;
}

.opportunity-list {
  margin-bottom: 20px;
}

.opportunity-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: transform 0.3s;
}

.opportunity-card:hover {
  transform: translateY(-5px);
}

.opportunity-cover {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.opportunity-info {
  padding: 10px;
}

.opportunity-title {
  margin: 0;
  font-size: 16px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.opportunity-stats {
  margin-top: 10px;
  display: flex;
  gap: 15px;
  color: #666;
  font-size: 14px;
}

.opportunity-time {
  margin-top: 5px;
  color: #999;
  font-size: 12px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 